package gui;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.logging.SimpleFormatter;

import org.apache.commons.lang3.text.StrBuilder;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;

import details.Cd;
import details.Comment;
import details.Like;
import details.Song;
import details.Target;
import details.Track;

import runnable_functions.ReferedObject;
import runnable_functions.USERfunctions;

/**
 * Logging Dialog ============== presents stores table for selection by user
 * program is initiated by selected store's view
 */
public class SongSearchResultsDialog extends org.eclipse.swt.widgets.Dialog {
	private static Display display;
	private static SongSearchResultsDialog inst;
	private static Shell shell;
	private static Shell dialogShell;
	private static Button searchDialogButtonSearchAlbum;
	private static Button searchDialogButtonSearchSong;
	private static Group logDialogGroup;
	private static boolean isLike;
	private static Text searchDialogAlbumTitleText;
	
	private static Text searchDialogAlbumPerformerText;
	private static Text searchDialogAlbumGenreText;
	private static Text searchDialogAlbumYearFromText;
	private static Text searchDialogAlbumYearToText;

	ArrayList<Comment> desireSongComments;
	
	private static Text searchDialogSongTitleText;
	private static Text searchDialogSongArtistText;
	private static Text searchDialogSongLyricText;

	Color color = new Color(display, 8, 164, 199);

	public static boolean successful = false;

	static Image background = new Image(display,Main.class.getResourceAsStream("headphone-music1.jpg"));
	static Image background2 = new Image(display,Main.class.getResourceAsStream("headphone-music2.jpg"));
	// Search results group
	private static Group searchGroupResults;
	private static Table searchTableAlbumResults;
	private static TableColumn searchTableColumnAlbum;
	private static TableColumn searchTableColumnArtist;
	private static TableColumn searchTableColumnYear;
	private static TableColumn searchTableColumnGenre;
	private static String lyric;

	//Album Details
	private static Group searchGroupDetails;
	private static Table searchTableSongResults;
	private static TableColumn searchTableColumnSongTrack;
	private static TableColumn searchTableColumnSongName;
	private static TableColumn searchTableColumnSongLength;
	private static Button searchButtonShowLyric;
	private static Button like;
	private static Button searchButtonShowLyric1;
	private static Button searchButtonShowLyric2;

	// Search options group
	private static Group searchGroupOptions;
	private static Button searchCheckBoxArtist;
	private static Text searchTextBoxArtist;
	private static Button searchCheckBoxSong;
	private static Text likeText;
	private static Button searchCheckBoxAlbum;
	private static Text searchTextBoxAlbum;
	private static Button searchCheckBoxLyric;
	private static Text searchTextBoxLyric;
	private static Button searchCheckBoxYear;
	private static Text searchTextBoxYear;
	private static Button searchCheckBoxGenre;
	private static Text searchTextBoxGenre;
	private static Button searchButtonClear;
	private static Button searchButtonSearch;
	private static Image cDcover;
	private static Button searchButtonShowSongs;
	private static ArrayList<Song> searchResult;
	private static String[] columnNames = {"Comment"};
	Date date;
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static Song desireSong;
	private static Button delete;  

	/**
	 * Auto-generated main method to display this org.eclipse.swt.widgets.Dialog
	 * inside a new Shell.
	 */
	public static void openSearchDialog() {
		try {
			display = Display.getDefault();
			shell = new Shell(display);
			shell.setLocation(Main.getCentral_x() - 406,
					Main.getCentral_y() - 458);
			shell.setSize(398, 200);
			//shell.setBackgroundImage(background);
			inst = new SongSearchResultsDialog(shell, SWT.NULL);
			inst.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void closeInitDialog() {
		shell.close();
	}

	public SongSearchResultsDialog(Shell parent, int style) {
		super(parent, style);
	}

	public void open() {
		try {
			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM
					| SWT.APPLICATION_MODAL);

			dialogShell.setText("Music Box");
			//dialogShell.setBackgroundImage(background);
			dialogShell.setLayout(null);
			{
				{
					searchGroupResults = new Group(dialogShell, SWT.NONE);
					searchGroupResults.setLayout(null);
					searchGroupResults.setBackgroundImage(background);
					//searchGroupResults.setText("Search Results");
					searchGroupResults.setBounds(0, -8, 790, 215);
					{
						searchTableAlbumResults = new Table(searchGroupResults,
								SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL
								| SWT.V_SCROLL | SWT.SINGLE); // single row
						// selection
						searchTableAlbumResults.setBounds(13, 23, 764, 148);
						searchTableAlbumResults.setHeaderVisible(true);
						searchTableAlbumResults.setLinesVisible(true);


						searchTableColumnAlbum = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnAlbum.setText("Title");
						searchTableColumnAlbum.setResizable(true);
						searchTableColumnAlbum.setMoveable(true);
						searchTableColumnAlbum.setWidth(275);


						searchTableColumnArtist = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnArtist.setText("Artist");
						searchTableColumnArtist.setResizable(true);
						searchTableColumnArtist.setMoveable(true);
						searchTableColumnArtist.setWidth(245);

						searchTableColumnGenre = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnGenre.setText("Genre");
						searchTableColumnGenre.setResizable(true);
						searchTableColumnGenre.setMoveable(true);
						searchTableColumnGenre.setWidth(122);

						searchTableColumnYear = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnYear.setText("Year");
						searchTableColumnYear.setResizable(true);
						searchTableColumnYear.setMoveable(true);
						searchTableColumnYear.setWidth(100);


						searchResult = Main.guiInt.getSongs();
						for (int i = 0; i < searchResult.size(); i++) {
							newEntry(searchResult.get(i).getName(),
									searchResult.get(i).getArtist());

						}

					}
					{
						searchButtonShowSongs = new Button(searchGroupResults,
								SWT.PUSH | SWT.CENTER);
						searchButtonShowSongs.setText("Show Song Details");
						searchButtonShowSongs.setBounds(245, 177, 340, 30);
						searchButtonShowSongs.addListener(SWT.Selection,
								new Listener() {
							
							public void handleEvent(Event event) {
								desireSong=null;
								Main.signal=null;
								if (searchTableAlbumResults.getSelectionIndex()!= -1){
									searchDialogAlbumTitleText.setText("");
								int index = searchTableAlbumResults.getSelectionIndex();
								desireSong =  Main.guiInt.getSongs().get(index);
								
									TableItem[] items = searchTableSongResults.getItems();//comments
									for (int i = 0; i < items.length ; i++) {
									if (items.length == 0) break;
									items[i].dispose();
									}
								

								Main.signal = new CountDownLatch(1);
								Main.dbGui.getSongAllInfo(desireSong.getIdNum());		
								try {
									Main.signal.await();
								} catch (InterruptedException e) {
									MessageBox messageBox = new MessageBox(
											SongSearchResultsDialog.shell, 32);
									messageBox.setText("Error");
									messageBox.setMessage("Error: "
											+ e.getLocalizedMessage());
									messageBox.open();
									e.printStackTrace();
								}

								String guiErrorMsg = Main.guiInt.getMassage();
								if (guiErrorMsg != null){
									MessageBox messageBox = new MessageBox(
											SongSearchResultsDialog.shell, 32);
									messageBox.setText("Login Form");
									messageBox.setMessage("Error: "
											+ guiErrorMsg);
									messageBox.open();
								}else{			
									desireSong = Main.guiInt.getSong();
									Main.guiInt.setLikes(desireSong.getLikes());
									System.out.println("the number of desired songs's likes is "+ desireSong.getLikes());
									desireSongComments = desireSong.getComments();
									Main.signal = new CountDownLatch(1);
									Main.dbGui.getIfUserLike(Target.SONG, Integer.toString(desireSong.getIdNum()), Main.getUser().getIdNum());
									try {
										Main.signal.await();
									} catch (InterruptedException e) {
										MessageBox messageBox = new MessageBox(
												SongSearchResultsDialog.shell, 32);
										messageBox.setText("Error");
										messageBox.setMessage("Error: "
												+ e.getLocalizedMessage());
										messageBox.open();
										e.printStackTrace();
									}
//popopo
									guiErrorMsg = Main.guiInt.getMassage();
									if (guiErrorMsg != null){
										MessageBox messageBox = new MessageBox(
												SongSearchResultsDialog.shell, 32);
										messageBox.setText("Song Search");
										messageBox.setMessage("Error: "
												+ guiErrorMsg);
										messageBox.open();
									}else{	
										likeText = new Text(searchGroupDetails, 1);
										isLike = Main.guiInt.getUserLike();
										if (isLike){
											like.setText("UnLike");
											likeText.setText("Likes: " + Main.guiInt.getLikes());	
										}else{
											like.setText("Like");
											likeText.setText("Likes: " + Main.guiInt.getLikes());
										}
										
									}
									for (int i = 0; i < desireSongComments.size(); i++) {
										newSongEntry(desireSongComments.get(i).getDate(),
												desireSongComments.get(i).getUser().getUserName(),
												desireSongComments.get(i).getComment()
												);
									}
									
									searchDialogAlbumGenreText = new Text(searchGroupDetails, 1);
									searchDialogAlbumGenreText.setText("Views: " +desireSong.getViews());
									//likeText.setText("Likes: " +desireCd.getLikes());
									searchDialogAlbumGenreText.setBounds(330, 100, 80, 30);
									searchTableSongResults.setBounds(403, 23, 374, 280);
									like.setBounds(320, 190, 60, 30);
									searchDialogAlbumTitleText.setBounds(23, 23, 280, 280);
									likeText.setBounds(330, 122, 80, 30);
									searchButtonShowLyric1.setBounds(33, 310, 264, 30);
									searchButtonShowLyric2.setBounds(610, 310, 164, 30);
									searchButtonShowLyric.setBounds(400, 310, 164, 30);
									
//									Group cd_cover = new Group(searchGroupDetails,
//											SWT.PUSH | SWT.CENTER);
//									cd_cover.setText("Cd Cover");
//									cd_cover.setBounds(13, 177, 340, 30);
//									if (Main.guiInt.getCdCover() != null){
//										cDcover = Main.guiInt.getCdCover();
//									}else{
//										cDcover = new Image(display,Main.class.getResourceAsStream("no-cover.jpg"));
//										
//									}
//									cd_cover.setBackgroundImage(cDcover);
										


								}
							}
						}}
								);
					}
					delete = new Button(searchGroupResults,
							SWT.PUSH | SWT.CENTER);
					delete.setText("Delete Song");
					delete.setBounds(645, 177, 100, 30);
					delete.addListener(SWT.Selection,
							new Listener() {
						public void handleEvent(Event event) {
							int index = searchTableAlbumResults.getSelectionIndex();
							desireSong =  Main.guiInt.getSongs().get(index);
							
							
							Main.signal = new CountDownLatch(1);
							Main.dbGui.delete(ReferedObject.SONG, Integer.toString(desireSong.getIdNum()), Main.getUser().getUserName());
							try {
								Main.signal.await();
							} catch (InterruptedException e) {
								MessageBox messageBox = new MessageBox(
										SongSearchResultsDialog.shell, 32);
								messageBox.setText("Error");
								messageBox.setMessage("Error: "
										+ e.getLocalizedMessage());
								messageBox.open();
								e.printStackTrace();
							}

							String guiErrorMsg = Main.guiInt.getMassage();
							if (guiErrorMsg != null){
								MessageBox messageBox = new MessageBox(
										SongSearchResultsDialog.shell, 32);
								messageBox.setText("Song Search");
								messageBox.setMessage("Error: "
										+ guiErrorMsg);
								messageBox.open();
							}else{	
								TableItem[] items = searchTableAlbumResults.getSelection();
								if (items.length == 0) return;
								items[0].dispose();
								MessageBox messageBox = new MessageBox(
										SongSearchResultsDialog.shell, 32);
								messageBox.setText("Song Search");
								messageBox.setMessage("song deleted seccesesfuly");
								messageBox.open();
							}
						}
					});
						
				}


				{
					searchGroupDetails = new Group(dialogShell, SWT.NONE | SWT.NO_BACKGROUND);
					searchGroupDetails.setLayout(null);
					searchGroupDetails.setBackgroundImage(background2);
					searchGroupDetails.setText("Song Lyric");
					searchGroupDetails.setBounds(5, 215, 787, 350);
					{
						searchTableSongResults = new Table(searchGroupDetails,
								SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL
								| SWT.V_SCROLL | SWT.SINGLE);
						
						searchTableSongResults.setHeaderVisible(true);
						searchTableSongResults.setLinesVisible(true);
						
						searchTableColumnSongTrack = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongTrack.setText("Time");
						searchTableColumnSongTrack.setResizable(true);
						searchTableColumnSongTrack.setMoveable(true);
						searchTableColumnSongTrack.setWidth(130);


						searchTableColumnSongTrack = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongTrack.setText("User");
						searchTableColumnSongTrack.setResizable(true);
						searchTableColumnSongTrack.setMoveable(true);
						searchTableColumnSongTrack.setWidth(80);

						searchTableColumnSongName = new TableColumn(
								searchTableSongResults, SWT.NONE);
						
						searchTableColumnSongName.setText("Comment");
						searchTableColumnSongName.setResizable(true);
						searchTableColumnSongName.setMoveable(true);
						searchTableColumnSongName.setWidth(160);

	
						
						
						
						{
							like = new Button(searchGroupDetails,
									SWT.PUSH | SWT.CENTER);
							like.setText("Like");
							
							like.addListener(SWT.Selection,
									
									new Listener() {
								public void handleEvent(Event event) {
									if(isLike == true){	
					
										Main.signal = new CountDownLatch(1);
										Main.dbGui.like_unlike(Target.SONG, Integer.toString(desireSong.getIdNum()), Main.getUser(), Like.UNLIKE);
										try {
											Main.signal.await();
										} catch (InterruptedException e) {
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
											e.printStackTrace();
										}

										String guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Login Form");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{
											isLike = !isLike;
										like.setText("Like");
										likeText.setText("Likes: " + Main.guiInt.getLikes());
									}
									}else if(isLike==false){
										Main.signal = new CountDownLatch(1);
										Main.dbGui.like_unlike(Target.SONG, Integer.toString(desireSong.getIdNum()), Main.getUser(), Like.LIKE);
										try {
											Main.signal.await();
										} catch (InterruptedException e) {
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
											e.printStackTrace();
										}

										String guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Login Form");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{
											isLike = !isLike;
										like.setText("UnLike");
										likeText.setText("Likes: " + Main.guiInt.getLikes());
									}
								}
							}});
							}
						
						
						
						
							searchButtonShowLyric = new Button(searchGroupDetails,
									SWT.PUSH | SWT.CENTER);
							searchButtonShowLyric.setText("Add comment");
							
							
							searchButtonShowLyric.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								if (searchTableAlbumResults.getSelectionIndex()!= -1){
								newCommentEntry();
								}
							}
							});
							
							searchButtonShowLyric2 = new Button(searchGroupDetails,
									SWT.PUSH | SWT.CENTER);
							searchButtonShowLyric2.setText("Delete comment");
							searchButtonShowLyric2.addSelectionListener(new SelectionAdapter() {
								public void widgetSelected(SelectionEvent e) {
									if (searchTableSongResults.getSelectionIndex()!= -1){
										Main.signal = new CountDownLatch(1);
										Main.dbGui.deleteCommentSong(Main.getUser(), desireSongComments.get(searchTableSongResults.getSelectionIndex()),desireSong.getIdNum());
										try {
											Main.signal.await();
										} catch (InterruptedException e1) {
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e1.getLocalizedMessage());
											messageBox.open();
											e1.printStackTrace();
										}

										String guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													SongSearchResultsDialog.shell, 32);
											messageBox.setText("Login Form");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{	
										
										
										
										
										TableItem[] items = searchTableSongResults.getSelection();
										if (items.length == 0) return;
										items[0].dispose();
										}
									}
									
								}
								});
							{
								
								searchDialogAlbumTitleText = new Text(searchGroupDetails, SWT.V_SCROLL);
								
								
							searchButtonShowLyric1 = new Button(searchGroupDetails,
									SWT.PUSH | SWT.CENTER);
							searchButtonShowLyric1.setText("Get Lyric");
							
							searchButtonShowLyric1.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								if (searchTableAlbumResults.getSelectionIndex()!= -1){
								searchDialogAlbumTitleText.setText("");
								if (desireSong.getLyric()== null){
								Main.signal = new CountDownLatch(1);
								Main.dbGui.getSongLyrics(desireSong);
								try {
									Main.signal.await();
								} catch (InterruptedException e1) {
									MessageBox messageBox = new MessageBox(
											SongSearchResultsDialog.shell, 32);
									messageBox.setText("Error");
									messageBox.setMessage("Error: "
											+ e1.getLocalizedMessage());
									messageBox.open();
									e1.printStackTrace();
								}
								String guiErrorMsg = Main.guiInt.getMassage();
								if (guiErrorMsg != null){
									MessageBox messageBox = new MessageBox(
											SongSearchResultsDialog.shell, 32);
									messageBox.setText("Login Form");
									messageBox.setMessage("Error: "
											+ guiErrorMsg);
									messageBox.open();
								}else{	
								
								
								
								searchDialogAlbumTitleText.setText(Main.guiInt.getLyric());
								}
								}else{
									{
									
									searchDialogAlbumTitleText.setText(desireSong.getLyric());
								
								}
						
								
							}}
							}});}}
							
							}
				
						}
					
			
				
			
			dialogShell.layout();
			dialogShell.pack();
			dialogShell.setLocation(getParent().toDisplay(100, 100));
			dialogShell.open();
			Display display = dialogShell.getDisplay();


			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public static Shell getDialogShell() {
		return dialogShell;
	}

	public static void setDialogShell(Shell dialogShell) {
		SongSearchResultsDialog.dialogShell = dialogShell;
	}


	public static Group getInitDialogGroup() {
		return logDialogGroup;
	}

	public static void setInitDialogGroup(Group logDialogGroup) {
		SongSearchResultsDialog.logDialogGroup = logDialogGroup;
	}

	public static Display getInitDisplay() {
		return display;
	}

	public static void setDisplay(Display display) {
		SongSearchResultsDialog.display = display;
	}

	public static Display getDisplay() {
		return display;
	}

	public static SongSearchResultsDialog getInst() {
		return inst;
	}

	public static Shell getShell() {
		return shell;
	}



	private void newEntry(String title, String artist) {
		String[] data = {title,artist};
		if (data != null) {
			TableItem item = new TableItem(searchTableAlbumResults, SWT.NONE);
			item.setText(data);
		}
	}
	private void newSongEntry(String date, String user, String comment) {
		String[] data = {date, user,comment};
		if (data != null) {
			TableItem item = new TableItem(searchTableSongResults, SWT.NONE);
			item.setText(data);
		}
	}
	private void newCommentEntry() {
		DataEntryDialog dialog = new DataEntryDialog(dialogShell);
		dialog.setLabels(columnNames);
		String[] data1 = dialog.open();
		date = new Date();
		String stringDate = df.format(date);
		if (data1 != null) {
		String[] data = {stringDate , Main.getUser().getUserName(), data1[0]};
		
			Main.signal = new CountDownLatch(1);
			Main.dbGui.addCommenToSong(Main.getUser(),  data1[0], stringDate, desireSong.getIdNum());	
			try {
				Main.signal.await();
			} catch (InterruptedException e) {
				MessageBox messageBox = new MessageBox(
						SongSearchResultsDialog.shell, 32);
				messageBox.setText("Error");
				messageBox.setMessage("Error: "
						+ e.getLocalizedMessage());
				messageBox.open();
				e.printStackTrace();
			}

			String guiErrorMsg = Main.guiInt.getMassage();
			if (guiErrorMsg != null){
				MessageBox messageBox = new MessageBox(
						SongSearchResultsDialog.shell, 32);
				messageBox.setText("Login Form");
				messageBox.setMessage("Error: "
						+ guiErrorMsg);
				messageBox.open();
			}else{	
			TableItem item = new TableItem(searchTableSongResults, SWT.NONE);
			item.setText(data);
			}
			
		}
	}
}
